package com.adu.music.spider;

import com.adu.music.parser.SongParser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author duchuanchuan
 * @date 2016/12/31
 */
public class SongUpdateSpider extends AbstractSpider {

    private int index = 0;
    private final int pageSize = 100;

    @Override
    protected void initTaskQueue() {
        List<Map<String, Object>> result = querySongsByIndex(index);
        result.forEach(map -> putTaskToQueue(map.get("id")));
        index++;
    }

    private List<Map<String, Object>> querySongsByIndex(int i) {
        Map<String, Integer> paramMap = new HashMap<>(2);
        paramMap.put("offset", i * pageSize);
        paramMap.put("size", pageSize);
        String querySql = "select id from song where comment > 999 limit :offset,:size";
        return asyncNamedParameterJdbcTemplate.queryForList(querySql, paramMap);
    }

    @Override
    protected void produceTask() {
        while (true) {
            List<Map<String, Object>> result = querySongsByIndex(index);
            result.forEach(map -> putTaskToQueue(map.get("id")));
            if (result.size() < pageSize) break;
            index++;
        }
    }

    @Override
    protected void consumeTask(Object task) {
        final String sql = "update song set comment=:comment,updated_at=now() where id=:id";
        String songId = String.valueOf(task);
        Map<String, Object> song = SongParser.parseSong(songId);
        Map<String, Object> paramMap = new HashMap<>(2);
        if (song.isEmpty()) return;
        paramMap.put("comment", song.get("comment"));
        paramMap.put("id", song.get("id"));
        asyncNamedParameterJdbcTemplate.update(sql, paramMap);
    }
}
